/**
This file is part of dbdjasperreport.

Copyright (C) 2008 Kue Vang aka Kou
Licensed under the Eclipse Public License, Version 1.0; 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at http://www.eclipse.org/legal/epl-v10.html 
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and limitations 
under the License.
**/

import groovy.sql.Sql

class CodeListService  implements java.io.Serializable{
    javax.sql.DataSource dataSource
	
    def List codeSourceList(Integer parameterId) throws Exception {
		def sql = getSql()
		def codeSourceList = []
		try{
			def param = ReportParameter.get(parameterId)
			def sqlStmt = param.parameterValue
			println "sqlStmt "+sqlStmt
		
			sql.eachRow(sqlStmt, {
				Code code = new Code()
				code.setId(it[0].toString())//PKey (first field ) 
				code.setCodeDesc(it[1])// description (second field)
				codeSourceList<<code
				}
			)
		}
		catch(Exception e){
			println "error in CodeListService.codeSourceList"
		}
		return codeSourceList
    }
	
	def List entitySourceList(Integer parameterId,String filterStr, Integer operatorId) throws Exception {
		def sql = getSql()
		def entitySourceList = []
		try{
			def param = ReportParameter.get(parameterId)
			def sqlStmt = param.parameterValue
			def whereClause = " WHERE UPPER(" +param.parameterValue2 +")"
			println "filterStr "+filterStr
			if(filterStr){
				if(operatorId == new Integer(OperatorService.strStartsWith))//starts with
					sqlStmt = sqlStmt + whereClause + " LIKE '" + filterStr.toUpperCase() +"%'"
				else if(operatorId == new Integer(OperatorService.strContains))//contains
					sqlStmt = sqlStmt + whereClause + " LIKE '%" + filterStr.toUpperCase() +"%'"
				else if(operatorId == new Integer(OperatorService.strMatchesExactly))//matches exactly
					sqlStmt = sqlStmt + whereClause + " = '" + filterStr.toUpperCase() +"'"
			}		
			println "added sql " + sqlStmt
			sql.eachRow(sqlStmt, {
				Code code = new Code()
				code.setId(it[0].toString())//PKey
				code.setCodeDesc(it[1])//description or the field you will search by
				entitySourceList<<code
				}
			)
		}
		catch(Exception e){
			println "error in CodeListService.entitySourceList"
		}
        return entitySourceList

    }
	
    private getSql(){
        return new Sql(dataSource)
    }
}